(function () {
  var titles = document.querySelectorAll(".menu span");
  var itemHeight = 30;
  var totalMS = 300;
  for (var i = 0; i < titles.length; i++) {
    titles[i].onclick = function () {
      // 之前有打开的要关闭
      var beforeOpened = document.querySelector(".sub-menu[status=opened");
      if (beforeOpened) {
        closeSubmenu(beforeOpened);
      }
      toggleSubmenu(this.nextElementSibling); // 传入当前节点的下一个兄弟节点
    };
  }

  // 打开
  function openSubmenu(subMenu) {
    var status = subMenu.getAttribute("status");
    if (status !== "closed" && status) {
      return;
    }
    subMenu.setAttribute("status", "playing");

    createAnimation({
      from: 0,
      to: itemHeight * subMenu.children.length,
      totalMS: totalMS,
      onMove: function (n) {
        subMenu.style.height = n + "px";
      },
      onEnd: function () {
        subMenu.setAttribute("status", "opened");
      },
    });
  }
  // 关闭
  function closeSubmenu(subMenu) {
    var status = subMenu.getAttribute("status");
    if (status !== "opened") {
      return;
    }
    subMenu.setAttribute("status", "playing");
    createAnimation({
      from: itemHeight * subMenu.children.length,
      to: 0,
      totalMS: totalMS,
      onMove: function (n) {
        subMenu.style.height = n + "px";
      },
      onEnd: function () {
        subMenu.setAttribute("status", "closed");
      },
    });
  }
  // 切换
  function toggleSubmenu(subMenu) {
    var status = subMenu.getAttribute("status");
    if (status === "playing") {
      // 正在播放动画
      return;
    } else if (status === "opened") {
      closeSubmenu(subMenu);
    } else {
      openSubmenu(subMenu);
    }
  }
})();
